package com.shujia.scala

import java.io.{BufferedReader, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo3IO {
  def main(args: Array[String]): Unit = {
    /**
     * 读取文件
     * 1、可以使用java中的方法
     * 2、在scala中有source
     *
     */

    //使用java的io流

    val bufferedReader = new BufferedReader(new FileReader("data/words.txt"))

    //读取第一行
    var line: String = bufferedReader.readLine()

    //判断下一行是否为空
    while (line != null) {
      println(line)

      //每次循环读取下一行
      line = bufferedReader.readLine()
    }

    bufferedReader.close()


    println("=" * 100)


    //scala的方式
    val bufferedSource: BufferedSource = Source.fromFile("data/words.txt")

    //读取所有行，得到一个迭代器
    val lines: Iterator[String] = bufferedSource.getLines()

    for (line <- lines) {
      println(line)
    }

    bufferedSource.close()

    /**
     * 写文件
     *
     */

    val fileWriter = new FileWriter("data/out1.txt")

    fileWriter.write("java")
    fileWriter.write("\n")
    fileWriter.write("java")
    fileWriter.write("\n")
    fileWriter.write("java")
    fileWriter.write("\n")
    fileWriter.write("java")
    fileWriter.close()

  }

}
